<template>
  <div class="app-container">
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
    <div style="margin: 15px 0;"></div>
    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
      <el-checkbox v-for="city in cities" :label="city.id" :key="city.id">{{ city.name }}</el-checkbox>
    </el-checkbox-group>

    <el-button style="margin-top: 20px" :disabled="buttonDisabled" type="primary" @click="setSysRoles">保存</el-button>

  </div>
</template>

<script>
import userApi from '@/api/acl/sysUser'

export default {
  data() {
    return {
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: true,
      userId: '',
      buttonDisabled: false
    }
  },

  created() {
    this.init()
  },

  methods: {
    init() {
      if (this.$route.params && this.$route.params.id) {
        this.userId = this.$route.params.id
        this.findRoles(this.userId)
      }
    },

    findRoles(userId) {
      userApi.findRoles(userId).then(response => {
        const assignRoles = response.data.assignRoles
        const checkedCitiesTemp = []
        assignRoles.filter(item => checkedCitiesTemp.push(item.id))
        this.checkedCities = checkedCitiesTemp
        this.cities = response.data.allRolesList
      })
    },

    setSysRoles() {
      this.buttonDisabled = true
      const roleIds = this.checkedCities.join(',')
      userApi.setSysRoles(this.userId, roleIds).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.$router.push({ path: '/acl/user/list' })
        }
      })
    },

    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    }
  }
}
</script>
